package servlet;

import dao.AddressDao;
import dao.GoodsDao;
import entity.Address;
import entity.Goods;
import entity.Order;
import entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;

@WebServlet("/buyServlet")
public class BuyServlet extends HttpServlet {
	
	@Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        doGet(request, response);
    }
	@Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {

		Order firstOrder = new Order();
		User user = (User) request.getSession().getAttribute("user");
		firstOrder.setUserId(user.getUserId());
		Integer goodId = Integer.valueOf(request.getParameter("goodId"));
		firstOrder.setGoodsId(goodId);
		BigDecimal goodPrice = new BigDecimal(request.getParameter("goodPrice"));
		firstOrder.setPrice(goodPrice);
		Integer goodQuantity = Integer.valueOf(request.getParameter("quantity"));
		firstOrder.setQty(goodQuantity);
		firstOrder.setOrderSum(goodPrice.multiply(new BigDecimal(goodQuantity)));
		System.out.println("ppppppppppppppp");
		System.out.println(goodPrice.multiply(new BigDecimal(goodQuantity)));
		String goodColor = request.getParameter("color");
		String goodSize = request.getParameter("size");
		String goodTaste = request.getParameter("taste");
		String goodModel = request.getParameter("modelNumber");
		// 拼接备注信息
		StringBuilder note = new StringBuilder();
		if (goodColor != null && !goodColor.isEmpty()) {
			note.append("颜色：").append(goodColor).append("  ");
		}
		if (goodSize != null && !goodSize.isEmpty()) {
			note.append("尺寸：").append(goodSize).append("  ");
		}
		if (goodTaste != null && !goodTaste.isEmpty()) {
			note.append("口味：").append(goodTaste).append("  ");
		}
		if (goodModel != null && !goodModel.isEmpty()) {
			note.append("型号：").append(goodModel).append("  ");
		}
		firstOrder.setNote(note.toString());
		GoodsDao dao = new GoodsDao();
		Goods good = dao.selectGoodByID(goodId);
		AddressDao addressDao = new AddressDao();
		List<Address> list = addressDao.selectMyAddress(user.getUserId());
		request.getSession().setAttribute("selectGood", good);
		request.getSession().setAttribute("myAddresses", list);
		request.getSession().setAttribute("firstOrder", firstOrder);
		response.sendRedirect("frontend/jiesuan.jsp");
	}


}
